#include"UdpClient.hpp"
#include<sys/types.h>
#include<sys/socket.h>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include <netinet/in.h>
#include <arpa/inet.h>
#include"Common.hpp"

int main(int argc,char *argv[])
{

    if(argc!=2)
    {
        std::cerr<<"Usage: "<<argv[0]<<" serverport"<<std::endl;
        Die(1);
    }

    u_int16_t serverport=std::stoi(argv[1]);
    
    //创建socket
    int sockfd=::socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0)
    {
        std::cerr<<"socket error"<<std::endl;
        Die(2);
    }
    //填充server信息
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=::htons(serverport);
    server.sin_addr.s_addr=INADDR_ANY;

    //client done
    while(true)
    {
        std::cout<<"Please Enter# ";
        std::string message;
        std::getline(std::cin,message);

        int n=::sendto(sockfd,message.c_str(),message.size(),0,CONV(&server),sizeof(server));
        if(n<=0) continue;
        char buffer[1024];
    
        struct sockaddr temp;
        socklen_t len=sizeof(temp);
        n=::recvfrom(sockfd,buffer,sizeof(buffer)-1,0,&temp,&len);
        buffer[n]=0;
        std::cout<<buffer<<std::endl;
    }
    return 0;
}